//查询
function searchList() {
    var createTime = ""
    if ($("#createTime").val() != "") {
        createTime = $("#createTime").val() + ' ' + '00:00:00'
    } else {
        createTime = ""
    }
    var createTimeEnd = ""
    if ($("#createTimeEnd").val() != "") {
        createTimeEnd = $("#createTimeEnd").val() + ' ' + '23:59:59'
    } else {
        createTimeEnd = ""
    }
    $.ajax({
        url: root.member.listPage,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            "pageNum": 1,
            "pageSize": 50,
            "mainCustomerName": $("#mainCustomerName").val(),
            "customerName": $("#customerName").val(),
            "customerCode": $("#customerCode").val(),
            "customerId": $("#customerId").val(),
            "createUser": $("#createUser").val(),
            "customerType": $("#customerType").val(),
            "createTime": createTime,
            "createTimeEnd": createTimeEnd,
            "mainCustomerCode": $("#mainCustomerCode").val(),
        }),
        success: function (data) {
            couponlist(data.data, 0);
            $('.M-box3').pagination({
                pageCount: data.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        /* root.member.adminMember2CList*/
                        url: root.member.listPage,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "pageNum": api.getCurrent(),
                            "pageSize": 50,
                            "mainCustomerName": $("#mainCustomerName").val(),
                            "customerName": $("#customerName").val(),
                            "customerCode": $("#customerCode").val(),
                            "customerId": $("#customerId").val(),
                            "createUser": $("#createUser").val(),
                            "customerType": $("#customerType").val(),
                            "createTime": createTime,
                            "createTimeEnd": createTimeEnd,
                            "mainCustomerCode": $("#mainCustomerCode").val(),
                        }),
                        success: function (result) {
                            couponlist(result.data);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
}
var dataSource = new Array();
var table;   //table对象
dataSource = [];
function couponlist(data, index) {
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data));
    dataSource.splice(0, dataSource.length);//清空数组
    if (data != null && data != '') {
        var datashu = data.startRow + 1;
        $.each(data.data, function (i, field) {
            var datashus = datashu++
            var rowData = new Array();
            rowData.push(field.mainCustomerId);
            rowData.push(field.mainCustomerCode);
            rowData.push(field.mainCustomerName);
            rowData.push(field.createTime);
            rowData.push(field.createUser);
            rowData.push(field.removeAble);
            rowData.push(datashus);
            rowData.push(field.isSetProductPoolRule);
            rowData.push(field.customerType);
            dataSource.push(rowData);

        });
    }
    initDataTable(dataSource);
    function initDataTable(dataSource) {

        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[6]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = "";
                        switch (row[8]) {
                            case 10:
                                val = "数采类型";
                                break;
                            case 20:
                                val = "Punch-Out数采平台审批";
                                break;
                            case 30:
                                val = "Punch-Out客户平台审批";
                                break;
                        
                            default:
                                val = "";
                                break;
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 5
                },
                {
                    "render": function (data, type, row, meta) {
                        // if (row[7] == true) {
                        //     var val = '<span class="powerButton 579 " style="position: absolute;margin: -45px 9px 0px -81px;"><a onclick="customerjump2(\'添加客户组\',\'account.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>组织相关管理</a></span><span class="powerButton 578 " style="position: absolute;margin: -45px -80px 5px 9px;"><a  onclick="customerjump2(\'正常商品\',\'normalCommodity.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>正常商品管理</a></span><span class="powerButton 637 " style="position: absolute;margin: -20px -73px 0px -81px;"><a  onclick="customerjump2(\'创建\',\'order_manage.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>配置中心</a></span><span class="powerButton 638 " style="position: absolute;margin: -20px -72px 0px 9px;"><a  onclick="customerjump2(\'创建\',\'temporary_goods.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>临采商品管理</a></span><span class="powerButton 639 " style="position: absolute;margin: 6px -102px 0px -81px;"><a  onclick="customerjump2(\'创建\',\'material_number.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>客户物料管理</a></span><span class="  "  style="position: absolute;margin: 6px -123px 0px 9px;" ><a onclick="customerjump2(\'轮播图管理\',\'carouselMap.html\',\'' + row[0] + '\',this)">轮播图管理</a></span><span class="powerButton 641 "  style="position: absolute;margin: 32px -123px 0px -81px;" ><a onclick="customerjump2(\'展示相关\',\'showRelevance.html\',\'' + row[0] + '\',this)">展示相关管理</a></span><span class=""  style="position: absolute;margin: 31px -123px 0px 9px;" ><a onclick="customerjump2(\'公告管理\',\'notice.html\',\'' + row[0] + '\',this)">公告管理</a></span><span class="powerButton 673"  style="position: absolute;margin: 57px -123px 0px -81px;" ><a onclick="customerjump2(\'销售合同\',\'salesContract.html\',\'' + row[0] + '\',this)">销售合同</a></span>';
                        // } else {
                        //     var val = '<span class="powerButton 579 " style="position: absolute;margin: -45px 9px 0px -81px;"><a onclick="customerjump2(\'添加客户组\',\'account.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>组织相关管理</a></span><span class="powerButton 578 " style="position: absolute;margin: -45px -80px 5px 9px;"><a  onclick="customerjump2(\'正常商品\',\'normalCommodity.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>正常商品管理</a></span><span class="powerButton 637 " style="position: absolute;margin: -20px -73px 0px -81px;"><a  onclick="customerjump2(\'创建\',\'order_manage.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>配置中心</a></span><span class="powerButton 638 " style="position: absolute;margin: -20px -72px 0px 9px;"><a  onclick="customerjump2(\'创建\',\'temporary_goods.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>临采商品管理</a></span><span class="powerButton 639 " style="position: absolute;margin: 6px -102px 0px -81px;"><a  onclick="customerjump2(\'创建\',\'material_number.html\',\'' + row[0] + '\',this)" data-type=' + row[2] + '>客户物料管理</a></span><span class="  "  style="position: absolute;margin: 6px -123px 0px 9px;" ><a onclick="customerjump2(\'轮播图管理\',\'carouselMap.html\',\'' + row[0] + '\',this)">轮播图管理</a></span><span class="powerButton 641 "  style="position: absolute;margin: 32px -123px 0px -81px;" ><a onclick="customerjump2(\'展示相关\',\'showRelevance.html\',\'' + row[0] + '\',this)">展示相关管理</a></span><span class=""  style="position: absolute;margin: 31px -123px 0px 9px;" ><a onclick="customerjump2(\'公告管理\',\'notice.html\',\'' + row[0] + '\',this)">公告管理</a></span><span class="powerButton 673"  style="position: absolute;margin: 57px -123px 0px -81px;" ><a onclick="customerjump2(\'销售合同\',\'salesContract.html\',\'' + row[0] + '\',this)">销售合同</a></span>';
                        // }

                        if (row[7] == true) {
                            var val = `
                            <div style="display:flex;justify-content:flex-end;flex-wrap: wrap;">
                                <span class="powerButton 579 " style="width:33%">
                                    <a onclick="customerjump2(\'编辑客户组\',\'newsigningAccountcreation.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>客户组信息管理</a>
                                </span>
                                <span class="powerButton 579 " style="width:33%">
                                    <a onclick="customerjump2(\'添加客户组\',\'account.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>组织相关管理</a>
                                </span>
                                <span class="powerButton 578 " style="width:33%">
                                    <a  onclick="customerjump2(\'正常商品\',\'normalCommodity.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>正常商品管理</a>
                                </span>
                                <span class="powerButton 641 " style="width:33%">
                                    <a onclick="customerjump2(\'展示相关\',\'displayRelated.html\',\'' + ${row[0]} + '\',this)">展示相关管理</a>
                                </span>
                                <span class="powerButton 637 " style="width:33%">
                                    <a  onclick="customerjump2(\'创建\',\'order_manage.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>配置中心</a>
                                </span>
                                <span class="powerButton 638 " style="width:33%">
                                    <a  onclick="customerjump2(\'创建\',\'temporary_goods.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>临采商品管理</a>
                                </span>
                                <span class="powerButton 673" style="width:33%">
                                    <a onclick="customerjump2(\'销售合同\',\'salesContract.html\',\'' + ${row[0]} + '\',this)">销售合同</a>
                                </span>
                                <span class="powerButton 639 " style="width:33%">
                                    <a  onclick="customerjump2(\'创建\',\'material_number.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>客户物料管理</a>
                                </span>
                            </div>
                            `
                        } else {
                            var val = `
                            <div style="display:flex;justify-content:flex-end;flex-wrap: wrap;">
                                <span class="powerButton 579 " style="width:33%">
                                    <a onclick="customerjump2(\'编辑客户组\',\'newsigningAccountcreation.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>客户组信息管理</a>
                                </span>
                                <span class="powerButton 579 " style="width:33%">
                                    <a onclick="customerjump2(\'添加客户组\',\'account.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>组织相关管理</a>
                                </span>
                                <span class="powerButton 578" style="width:33%">
                                    <a  onclick="customerjump2(\'正常商品\',\'normalCommodity.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>正常商品管理</a>
                                </span>
                                <span class="powerButton 641 " style="width:33%">
                                    <a onclick="customerjump2(\'展示相关\',\'displayRelated.html\',\'' + ${row[0]} + '\',this)">展示相关管理</a>
                                </span>
                                <span class="powerButton 637" style="width:33%">
                                    <a  onclick="customerjump2(\'创建\',\'order_manage.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>配置中心</a>
                                </span>
                                <span class="powerButton 638" style="width:33%">
                                    <a  onclick="customerjump2(\'创建\',\'temporary_goods.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>临采商品管理</a>
                                </span>
                                <span class="powerButton 673" style="width:33%">
                                    <a onclick="customerjump2(\'销售合同\',\'salesContract.html\',\'' + ${row[0]} + '\',this)">销售合同</a>
                                </span>
                                <span class="powerButton 639 " style="width:33%">
                                    <a  onclick="customerjump2(\'创建\',\'material_number.html\',\'' + ${row[0]} + '\',this)" data-type='${row[2]}'>客户物料管理</a>
                                </span>
                            </div>
                            `
                        }
                        return val;
                    },
                    "targets": 6
                }


            ]
        });
        //权限控制函数
        power()
    };
}


//修改名称
var index = 0;
function confirm(id, name) {

    var names = name.getAttribute("data-type")
    console.log(names)
    var curInd = layer.confirm(
        '<span>客户组名称：</span><input oninput="checkMaxIut(this)" autocomplete="off" placeholder="请输入客户组名称"  id="mainCustomername" value=' + names + '>' + '<br/>', { title: '客户组名称', btn: ['确定', '取消'] }, function (index) {

            finish2(id, names)
            layer.close(curInd);

        }, function () {
            layer.close(curInd);

        });
}
function finish2(id, name) {
    $.ajax({
        url: root.member.mainCustomerupdate,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            "mainCustomerId": id,
            "mainCustomerName": $("#mainCustomername").val(),
            "updateUser": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
        }),
        success: function (data) {
            if (data.errorCode == 0) {
                $.Huimodalalert('修改成功！', 2000);
                searchList()
            } else {
                showMsg(5, data.msg);
            }
        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
    layer.close(index);
}
//弹框
function showMsg(icon, msg) {
    layer.msg(msg, {
        icon: icon,
        time: 1000
    });
}



//删除
function mainCustomerdelete(val, id) {
    var curInd = layer.confirm(
        '<span>确定要删除此客户组吗？</span>' + '<br/>', { title: '客户组名称', btn: ['确定', '取消'] }, function (index) {

            customerdelete(id)
            layer.close(curInd);

        }, function () {
            layer.close(curInd);

        });

}
function customerdelete(id) {
    $.ajax({
        url: root.member.deleteBatchByIds,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            "ids": id,
        }),
        success: function (data) {
            if (data.errorCode == 0) {
                $.Huimodalalert('删除成功！', 2000);
                searchList()
            } else {
                showMsg(5, data.msg);
            }
        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
    layer.close(index);
}

    //取消
    function closeLayer(data) {
        window.parent.saveOK(data);
        window.parent.searchList();
        var index = parent.layer.getFrameIndex(window.name);  // 关闭当前页面，并不刷新父级页面
        parent.layer.close(index);
        
    }

//添加
function customeradd(url,title) {
    // var curInd = layer.confirm(
    //     '<span>客户组名称：</span><input  id="mainCustomernames" onkeyup="replaceLikeVal(this)"   oninput="checkMaxIut(this)" autocomplete="off" placeholder="请输入客户组名称">' + '<br/>', { title: '客户组名称', btn: ['确定', '取消'] }, function (index) {

    //         mainCustomernameadd()
    //         layer.close(curInd);

    //     }, function () {
    //         layer.close(curInd);

    //     });
    sessionStorage.removeItem('mainCustomerId')
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

//账号对接失败
function customerError(url,title) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

function mainCustomernameadd() {
    $.ajax({
        url: root.member.mainCustomersave,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            "status": 10,
            "mainCustomerName": $("#mainCustomernames").val(),
            "createUser": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,/*JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name*/
            "updateUser": ""
        }),
        success: function (data) {
            if (data.errorCode == 0) {
                $.Huimodalalert('创建成功！', 2000);
                searchList()
            } else {
                showMsg(5, data.msg);
            }
        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });
    layer.close(index);
}
//跳转添加主客户页面
function customerjump2(title, url, id, name) {
    var names = name.getAttribute("data-type")
    sessionStorage.setItem("mainCustomerId", id)
    sessionStorage.setItem("mainCustomerName", names);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
//主客户限制字符
var len
var Preser
var common = 100//要限制输入的字数
function checkMaxIut(me) {
    var text = $(me).val()
    strlen(text)
    if (len > common) {
        $(me).val(Preser)
    } else {
        Preser = $(me).val()
    }
}
function strlen(str) {
    len = 0;
    for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            len++;
        } else {
            len += 2;
        }
    }
    return len;
}
//使用人限制字符
var len2
var Preser2
var common2 = 20//要限制输入的字数
function checkMaxIut2(me) {
    var text = $(me).val()
    strlen2(text)
    if (len2 > common2) {
        $(me).val(Preser2)
    } else {
        Preser2 = $(me).val()
    }
}
function strlen2(str) {
    len2 = 0;
    for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            len2++;
        } else {
            len2 += 2;
        }
    }
    return len2;
};
//手工同步
function maztion(id) {
    var paramsd = {
        "mainCustomerId": Number(id)
    };
    var succCallBack = function (data, status, response) {
        if (data.errorCode == 0) {
            $.Huimodalalert(data.msg, 2000);
        } else {
            $.Huimodalalert(data.msg, 2000);
        }
    }
    web.doAjax(root.member.synchProductPoolRule, 'post', paramsd, succCallBack);
}

function saveOK(data){
    if(data == 'save'){
        $.Huimodalalert('更新成功！', 2000);
    }else if(data == 'up'){
        $.Huimodalalert('创建成功！', 2000);
    }
    
}